package com.tiger.cloud.common.mapper;

import java.io.IOException;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang3.StringUtils;
import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import com.fasterxml.jackson.core.JsonGenerator;
import com.tiger.cloud.util.MagicConstants;

public class CallbackMappingJackson2HttpMessageConverter extends MappingJackson2HttpMessageConverter {

	@Override
	protected void writePrefix(JsonGenerator generator, Object object) throws IOException {
		HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.currentRequestAttributes()).getRequest();
		String callbackParam = request.getParameter(MagicConstants.JSONP_CALLBACK);
		if (!StringUtils.isEmpty(callbackParam)) {
			//generator.writeRaw("/**/");
			generator.writeRaw(callbackParam+ "(");
		} else {
			super.writePrefix(generator, object);
		}
	}
	
	@Override
	protected void writeSuffix(JsonGenerator generator, Object object) throws IOException {
		HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.currentRequestAttributes()).getRequest();
		String callbackParam = request.getParameter(MagicConstants.JSONP_CALLBACK);
		if (!StringUtils.isEmpty(callbackParam)) {
			generator.writeRaw(");");
		} else {
			super.writeSuffix(generator, object);
		}
	}
 
}